package player.bum.vn;

import player.bum.vn.common.LinkUtils;
import player.bum.vn.js.WebAppInterfaceImp;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.ActionBarActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.DownloadListener;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
	WebView						webView;

//	public static final String	SITE_URL	= "http://local.bum.vn/html/clip/home";

	public static final String	SITE_URL	= "http://bum.vn/html/clip/home";

	@SuppressLint({
			"JavascriptInterface", "SetJavaScriptEnabled"
	})
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.webview);
		String deviceId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);

		if (webView == null) {
			webView = (WebView) findViewById(R.id.webview);
			WebSettings settings = webView.getSettings();
			settings.setJavaScriptEnabled(true);
			settings.setDomStorageEnabled(true);
			settings.setNeedInitialFocus(true);
			webView.requestFocus();
			webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
			webView.setScrollbarFadingEnabled(true);
			webView.getSettings().setLoadsImagesAutomatically(true);

			webView.addJavascriptInterface(new WebAppInterfaceImp(this, webView), "BUMAPK");

			webView.setWebViewClient(new MyWebViewClient(deviceId));
			webView.setWebChromeClient(new MyWebChromeClient());

			webView.setDownloadListener(new DownloadListener() {
				@Override
				public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
					Intent i = new Intent(Intent.ACTION_VIEW);
					i.setData(Uri.parse(url));
					startActivity(i);
				}
			});

			webView.setBackgroundColor(Color.WHITE);
			webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
		}

		if (savedInstanceState == null) {
			webView.loadUrl(LinkUtils.resolvePath(SITE_URL, deviceId));
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		webView.saveState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		webView.restoreState(savedInstanceState);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu m) {
		new MenuInflater(this).inflate(R.menu.main, m);
		return super.onCreateOptionsMenu(m);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			if (webView.canGoBack()) {
				webView.goBack();
			} else {
				new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle(R.string.quit).setMessage(R.string.really_quit)
						.setInverseBackgroundForced(true)
						.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								MainActivity.this.finish();
							}
						}).setNegativeButton(R.string.no, null).show();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.mn_reload:
				webView.reload();
				break;
		}
		return super.onOptionsItemSelected(item);
	}

	private class MyWebViewClient extends WebViewClient {
		String	deviceId;

		public MyWebViewClient(String cid) {
			this.deviceId = cid;
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			if (Uri.parse(url).getHost().endsWith("bum.vn")) {
				url = LinkUtils.resolvePath(url, deviceId);
				view.loadUrl(url);
				return true;
			}

			return false;
		}

		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
		}
	}

	final Activity	activity	= this;

	private class MyWebChromeClient extends WebChromeClient {
		@Override
		public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
			String title = "Thông báo";
			int idx = message.indexOf("\n");
			if (idx > 0) {
				title = message.substring(0, idx);
				message = message.substring(idx + 1);
			}

			new AlertDialog.Builder(view.getContext()).setIcon(android.R.drawable.ic_dialog_alert).setTitle(title).setMessage(message)
					.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							result.confirm();
						}
					}).setCancelable(false).create().show();

			return true;
		}
	}
}
